'use strict';
/**
 * 用户管理服务类
 */
const Service = require('egg').Service;
class AdminService extends Service {

  /**
   * 分页查询
   * @param page 页数 
   */
  async getAdminPageList(page) {
    const { ctx } = this;
    //每页数量
    let pageSize = 8;
    let query = {
      offset: (page - 1) * pageSize,
      limit: pageSize,
      order: [['id', 'desc']],
      include: [{
        model: ctx.model.Role
      }
      ]
    };
    let count = await ctx.model.Admin.count();
    let result = await ctx.model.Admin.findAll(query);
    console.log('result' + result)
    // let totalPages = Math.ceil(count / pageSize);
    let pageList = {
      list: result,
      pageSize: pageSize,
      page: page,
      total: count
    };
    return pageList;
  }

  /**
   * 新建
   * @param name 名称
   * @param password 密码 
   */
  async saveAdmin({ id, name, password ,role}) {
    const { ctx, logger } = this;
    let result = null;
    if (id != 'undefined' && id != null) {
      let admin = await ctx.model.Admin.findById(id);
      if (!admin) {
        return false;
      }
      result = await admin.update({ name: name, password: password ,role_id:role});
    } else {
      result = await ctx.model.Admin.create({ name: name, password: password,role_id:role });
    }

    if (!result) {
      return false;
    }
    logger.info('***admin***返回结果->{}******', result);
    return result;
  }

  /**
   * 删除
   * @param id  
   */
  async deleteAdmin(id) {
    const { ctx } = this;
    let admin = await ctx.model.Admin.findById(id);
    if (!admin) {
      return false;
    }
    let result = await admin.destroy();
    return result;
  }
}

module.exports = AdminService;
